package com.zhenyi.zhengfang.miniapp;

import java.util.Date;

import com.cjw.model.DBMap;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.utils.AuthUtils;
import com.zhengfang.common.model.ZfUser;
import com.zhenyi.core.AES;
import com.zhenyi.youqu.core.ZHSMSUtils;
import com.zhenyi.zhengfang.core.ZFMiniAppController;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class AuthController  extends ZFMiniAppController{
	private final String CACHE_KEY = "-zhengfang";
	private final String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";
	/**
	 * 通过code换取openId,仅仅获取openId
	 */
	public void openId() {
		String code = getPara("code");
		if (StrKit.isBlank(code)) {
			renderFailure();
			return;
		}
		String appid = getPara("appid", "");
		String appSecret = "";
		if (StrKit.isBlank(appid)) {
			appid = APP_ID;
			appSecret = APP_SECRET;
		} else {
			appSecret = PropKit.get(appid);
		}
		String url = StrFormatter.format(code2SessionUrl, appid, appSecret, code);
		String response = HttpKit.get(url);
		JSONObject jsonObject = JSONUtil.parseObj(response);
		String openId = jsonObject.getStr("openid");
		String unionid = jsonObject.getStr("unionid");
		String session_key = jsonObject.getStr("session_key");
		Integer errcode = jsonObject.getInt("errcode");
		if (errcode != null) {
			String errmsg = jsonObject.getStr("errmsg");
			LogKit.warn("jscode2session error " + errmsg);
			renderFailure();
			return;
		}
		DBMap map = new DBMap();
		map.put("openId", openId);
		Cache cache = Redis.use();
		cache.setex(openId + CACHE_KEY, 3600 * 24, session_key);
		renderSuccess(map);

	}

}
